import Cookies from 'js-cookie'
import store from '@/store'

const TokenKey = 'Admin-Token'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  console.log(token, 'set')
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

let isLoading = false
export function refreshTokenTime() {
  if (isLoading) return
  const expiresIn = localStorage.getItem('expiresIn')
  const expireSeconds = expiresIn - Date.now() / 1000
  if (expireSeconds <= 10 * 60 && expireSeconds > 0) {
    console.log(expireSeconds, 'token快要过期了')
    // token即将过期，刷新token
    isLoading = true
    store.dispatch('user/refreshToken').then(() => {
      isLoading = false
    })
  }
}
